<script setup lang="ts">
  import { login, getUserInfo } from '~/apis/user'
  definePageMeta({
    layout: 'auth',
    middleware: 'auth'
  })

  useSeoMeta({
    title: '登录'
  })
  const userStore = useUserStore()
  const toast = useToast()
  const route = useRoute()
  const router = useRouter()
  const loading = ref(false)
  const fields = [
    {
      name: 'username',
      type: 'text',
      label: '用户名',
      placeholder: '请输入用户名'
    },
    {
      name: 'password',
      label: '密码',
      type: 'password',
      placeholder: '请输入密码',
      showPassword: true
    }
  ]

  const validate = (state: any) => {
    const errors = []
    if (!state.username) errors.push({ path: 'username', message: '用户名不能为空' })
    if (!state.password) errors.push({ path: 'password', message: '密码不能为空' })
    if (state.password.length > 24 || state.password.length < 6)
      errors.push({ path: 'password', message: '密码为6-24位' })
    return errors
  }

  async function onSubmit(d: any) {
    try {
      loading.value = true
      const { data, pending } = await login(Object.assign({}, d))
      if (data.value) {
        userStore.setToken(data.value.token)
        await getInfo()
      }
      loading.value = pending.value
    } catch (error) {}
  }

  async function getInfo() {
    try {
      const { data } = await getUserInfo()
      if (data.value) {
        userStore.setUserInfo(data.value)
        toast.add({ title: '登录成功', icon: 'i-heroicons-check-circle-solid', color: 'primary' })
        const redirect = route.query.redirect ?? '/'
        const toPath = decodeURIComponent(redirect as string)
        if (toPath) {
          router.replace(toPath)
        } else {
          router.replace('/')
        }
      }
    } catch (error) {}
  }
</script>

<template>
  <UCard class="max-w-sm w-full bg-white/75 dark:bg-white/5 backdrop-blur">
    <UAuthForm
      :fields="fields"
      :validate="validate"
      title="欢迎回来"
      align="top"
      :ui="{ base: 'text-center', footer: 'text-center' }"
      :submit-button="{ label: '登录' }"
      :loading="loading"
      @submit="onSubmit"
    >
      <template #description>
        没有账户?
        <NuxtLink
          :to="$route.query.redirect ? '/signup?redirect=' + $route.query.redirect : '/signup'"
          class="text-primary font-medium"
          >注册</NuxtLink
        >
      </template>

      <!-- <template #password-hint>
        <NuxtLink to="/" class="text-primary font-medium">忘记密码?</NuxtLink>
      </template> -->
    </UAuthForm>
  </UCard>
</template>
